<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>上传 CSV 文件</title>
</head>
<body>
    <h1>上传 CSV 文件</h1>
    <form id="csvUploadForm">
        <label for="speciesName">物种名称：</label>
        <input type="text" id="speciesName" name="speciesName" required>
        <br><br>
        <label for="csvFile">选择 CSV 文件：</label>
        <input type="file" id="csvFile" name="csvFile" accept=".csv" required>
        <br><br>
        <button type="submit">上传并导入数据库</button>
    </form>

    <div id="message"></div>

    <script>
        document.getElementById('csvUploadForm').addEventListener('submit', function(event) {
            event.preventDefault();

            const speciesName = document.getElementById('speciesName').value;
            const fileInput = document.getElementById('csvFile');
            const file = fileInput.files[0];

            if (file) {
                const formData = new FormData();
                formData.append('csvFile', file);

                const messageDiv = document.getElementById('message');
                messageDiv.innerHTML = '文件上传中...';

                fetch(`http://localhost:4000/upload-csv/${encodeURIComponent(speciesName)}`, {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.json();
                })
                .then(data => {
                    messageDiv.innerHTML = data.message || '文件上传成功！';

                    // 将结果保存到 localStorage
                    localStorage.setItem('importedtrackData', JSON.stringify(data.data));
                    console.log('数据已保存到 localStorage');
                })
                .catch(error => {
                    messageDiv.innerHTML = '上传失败：' + error.message;
                    console.error('错误:', error);
                });
            } else {
                document.getElementById('message').innerHTML = '请先选择一个 CSV 文件。';
            }
        });
    </script>
</body>
</html>